package com.quickcode.example.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 并行化
 */
@Slf4j
public class CompletableFutureExample3 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> server1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                log.error("线程异常：{}",e);
            }
            return "192.168.0.1";
        });

        CompletableFuture<String> server2 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                log.error("线程异常：{}",e);
            }
            return "192.168.0.2";
        });

        CompletableFuture<String> result = server1.applyToEither(server2, new Function<String, String>() {
            @Override
            public String apply(String s) {
                log.info("响应更快的：{}",s);
                return s;
            }
        });

        log.info("result:{}",result.get());
    }
}